package www.my.imageframecompare.multiImgContinue;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import www.my.imageframecompare.Constant;
import www.my.imageframecompare.R;
import www.my.imageframecompare.okhttpDwonload.DonwloadResponseListener;
import www.my.imageframecompare.okhttpDwonload.OKHttpUtils;

/**
 * 缓存多图
 */
public class MultiViewContinueActivity extends AppCompatActivity {
    private static final String TAG = "MultiViewContinueActivi";
    private EditText etNum;
    private FrameLayout fr1, fr2;
    private ImageView iv1, iv2;
    private ExecutorService pool;
    private String downLoadAddress;
    private List<PlayDataModel> playList;
    private boolean[] isDownlaod;
    private MyTimer mIv1Timer = new MyTimer() {
        @Override
        public void onFinish(int index) {
            Log.i(TAG, "onFinish: ==" + index + "  thread name==" + Thread.currentThread().getName());
            getNextPlayData(index);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        downLoadAddress = getFilesDir().getAbsolutePath() + File.separator + "images" + File.separator;
        if (!new File(downLoadAddress).exists()){
            new File(downLoadAddress).mkdirs();
        }
        setContentView(R.layout.activity_cache_view);
        pool = Executors.newFixedThreadPool(4);
        isDownlaod = new boolean[Constant.imageUrls.length];
        //缓存部分图片
        pool.execute(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "run: start download");
                for (int i = 0; i < Constant.imageUrls.length; i++) {
                    final String imageUrl = Constant.imageUrls[i];
                    final int dex = i;
                    OKHttpUtils.instance().donwloadFile(downLoadAddress, imageUrl, i + (imageUrl.contains(".gif") ? ".gif":".jpg" ), new DonwloadResponseListener() {
                        @Override
                        public void OnSuccess(long bytesRead, long contentLength, boolean done) {

                        }

                        @Override
                        public void onfailure() {
                            Log.e(TAG, "onfailure: " + imageUrl + "  dex==" + dex);
                        }

                        @Override
                        public void onSuccess(File file) {
                            isDownlaod[dex] = true;
                            Log.i(TAG, "onSuccess: " + file.getAbsolutePath()+ " dex==" + dex+  " thread name=="+ Thread.currentThread().getName());
                        }
                    });

                }
            }
        });
        etNum = (EditText) findViewById(R.id.et_img_index);
        fr1 = (FrameLayout) findViewById(R.id.fr1);
        fr2 = (FrameLayout) findViewById(R.id.fr2);
        iv1 = (ImageView) findViewById(R.id.iv1);
        iv2 = (ImageView) findViewById(R.id.iv2);

        //图片数据
        playList = new ArrayList<>();
        for (int i = 0; i < Constant.imageUrls.length; i++) {
            PlayDataModel playDataModel = new PlayDataModel();
            playDataModel.setUrl(Constant.imageUrls[i]);
            playDataModel.setDataType(PlayDataModel.DataType.PICTURE);
            playDataModel.setPlayTime(2 + i * 2);
            playList.add(playDataModel);
        }



    }

    private boolean getNextPlayData(int currentIndex) {
        Log.i(TAG, "getNextPlayData:  thredName=="+Thread.currentThread().getName());
        //load next
        int startIndex = ((currentIndex + 1 >= Constant.imageUrls.length) ? 0 : (currentIndex + 1));
        for (int i = startIndex; (i < isDownlaod.length); i++) {
            final PlayDataModel playDataModel = playList.get(i);
            final int index = i;
            String url = playDataModel.getUrl();
            final String s = downLoadAddress + i + (url.contains(".gif") ? ".gif" : ".jpg");
            if (isDownlaod[i] && new File(s).exists()) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                                    iv1.setImageBitmap();
                        if (s.contains(".gif")) {
                            Glide.with(MultiViewContinueActivity.this)
                                    .load(s)
                                    .asGif()
                                    .into(iv1);
                        } else {
                            Glide.with(MultiViewContinueActivity.this)
                                    .load(s)
                                    .into(iv1);
                        }
                        Log.i(TAG, "run: Glide load img index== "+index + s);
                    }
                });
                mIv1Timer.init(playDataModel.getPlayTime() * 1000, 50, index);
                mIv1Timer.start();
                Log.i(TAG, "run: 找到开始任务 跳出循环 ");

                return true;
            }
        }
        return false;
    }

    public void clickNext(View view) {

    }

    public void turnIndexImg(View view) {
    }

    public void loopPlay(View view) {
    }

    public void startImgTurn(View view) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (getNextPlayData(0)) {
                        break ;
                    }
                    try {
                        Thread.sleep(50);//防止所有任务都没有下载时 空循环
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void stopImgTurn(View view) {
        mIv1Timer.cancel();
    }
}
